"use client"
import {FormProvider, useForm} from "react-hook-form";
import {FormField, FormLabel} from "@/components/ui/form";
import {Input} from "@/components/ui/input";
import {z} from "zod";
import {RoleSearchFormSchema} from "@/lib/zod/schema";
import {zodResolver} from "@hookform/resolvers/zod";
import {Button} from "@/components/ui/button";
import {ColumnDef, flexRender, getCoreRowModel, useReactTable} from "@tanstack/react-table";
import {Roles} from "@/lib/db/types";
import {useCallback, useEffect, useState} from "react";
import {getSearchParams} from "@/lib/utils";
import {toast} from "sonner";
import {Table, TableBody, TableCell, TableHead, TableHeader, TableRow} from "@/components/ui/table";
import {DataTablePagination} from "@/components/page/data-table-pagination";
import {Checkbox} from "@/components/ui/checkbox";
import {RotateCcw, Search, UserRoundPlus} from "lucide-react";
import {useRouter} from "next/navigation";



const Page = () => {
  const form = useForm<z.infer<typeof RoleSearchFormSchema>>({
    resolver:zodResolver(RoleSearchFormSchema),
    defaultValues:{
      roleName:"",
      roleCode:"",
    }
  });
  const router = useRouter();
  const [roleAndRowCount, setRoleAndRowCount] = useState<{ data: Array<Roles>, rowCount: number }>({data: [], rowCount: 0});
  const [pagination, setPagination] = useState({pageIndex: 0,pageSize: 10});
  const searchRole = useCallback((data:z.infer<typeof RoleSearchFormSchema>)=> {
    const searchParams = getSearchParams({...data,...pagination});
    fetch(`/api/roles?${searchParams}`)
        .then((rs)=>rs.json())
        .then(({code,data,msg})=>{
          if(code === 200){
            setRoleAndRowCount(()=>{
              return {rowCount: data.rowCount, data: data.data};
            })
            return;
          }
          toast("系统异常",{
            description:msg,
            duration:1000,
            action:{
              label:"取消",
              onClick:()=>{}
            }
          })
        })
  },[pagination])

  useEffect(() => {
    searchRole({});
  }, [searchRole]);

  const cols:ColumnDef<Roles>[]=[
      {
        accessorKey:"roleId",
        header: ({ table }) => {
          return <span className={"flex items-center gap-2"}>
                    <Checkbox
                        id={"select_all_id"}
                        checked={
                            table.getIsAllPageRowsSelected() ||
                            (table.getIsSomePageRowsSelected() && "indeterminate")
                        }
                        onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
                        aria-label="全选"
                    />
                    <label htmlFor={"select_all_id"} className={"hidden lg:block"}>全选</label>
                </span>
        },
        cell: ({ row }) => {
          return  <Checkbox
              checked={row.getIsSelected()}
              onCheckedChange={(value) => row.toggleSelected(!!value)}
              aria-label="选择行" className={"flex items-center"}
          />
        },
      },
      {
        accessorKey:"roleCode",
        header:"角色编码",
      },
      {
        accessorKey:"roleName",
        header:"角色名",
      },
      {
        accessorKey:"createdAt",
        header:"创建日期",
      },
      {
        accessorKey:"updatedAt",
        header:"更新日期",
      },
  ];

  const table = useReactTable<Roles>({
    data: roleAndRowCount.data,
    rowCount: roleAndRowCount.rowCount,
    columns: cols,
    getCoreRowModel: getCoreRowModel(),
    onPaginationChange: setPagination,
    //必须设置手动否则会陷入死循环
    manualPagination: true,
    state: {
      pagination,
    },
  });

  return <>
    <div className={"flex flex-col p-4"}>
      <FormProvider {...form}>
        <form onSubmit={form.handleSubmit(searchRole)} className={"flex flex-col  md:grid md:grid-cols-2 lg:grid-cols-3 gap-2"}>
          {/*搜索条件*/}
          <FormField render={({field})=>{
            return <div className={"flex items-center gap-2 "}>
              <FormLabel className={"flex-shrink-0 w-20"}>角色名:</FormLabel>
              <Input {...field} />
            </div>
          }} name={"roleName"} control={form.control}/>

          <FormField render={({ field})=> {
            return <div  className={"flex items-center gap-2 "}>
              <FormLabel  className={"flex-shrink-0 w-20"}>角色编码:</FormLabel>
              <Input {...field} />
            </div>
          }} name={"roleCode"} control={form.control}/>
          <div className={"flex items-center justify-start gap-2"}>
            <Button variant={"outline"} size={"sm"} type={"submit"}>
              <Search/>
              <span className={"hidden md:block"}>搜索</span>
            </Button>

            <Button variant={"outline"} size={"sm"} type={"button"} onClick={() => {
              form.reset();
              searchRole({});
            }}>
              <RotateCcw/>
              <span className={"hidden md:block"}>重置</span>
            </Button>
            <Button variant={"outline"} size={"sm"} type={"button"} onClick={() => {
              router.push("/home/role/add");
            }}>
              <UserRoundPlus/>
              <span className={"hidden md:block"}>新建</span>
            </Button>
          </div>
        </form>
      </FormProvider>
      <div>
        <div className={"rounded-md mt-4 md:border"}>
          <Table className={"hidden md:table"}>
            <TableHeader>
              {table.getHeaderGroups().map((headerGroup) => (
                  <TableRow key={headerGroup.id}>
                    {headerGroup.headers.map((header) => {
                      return (
                          <TableHead key={header.id}>
                            {header.isPlaceholder
                                ? null
                                : flexRender(
                                    header.column.columnDef.header,
                                    header.getContext()
                                )}
                          </TableHead>
                      )
                    })}
                  </TableRow>
              ))}
            </TableHeader>
            <TableBody>
              {table.getRowModel().rows?.length ? (
                  table.getRowModel().rows.map((row) => (
                      <TableRow
                          key={row.id}
                          data-state={row.getIsSelected() && "selected"}
                      >
                        {row.getVisibleCells().map((cell) => (
                            <TableCell key={cell.id}>
                              {flexRender(cell.column.columnDef.cell, cell.getContext())}
                            </TableCell>
                        ))}
                      </TableRow>
                  ))
              ) : (
                  <TableRow>
                    <TableCell colSpan={cols.length} className="h-24 text-center">
                      无数据
                    </TableCell>
                  </TableRow>
              )}
            </TableBody>
          </Table>
          <div className={"flex flex-col gap-3 md:hidden"}>
       {/*     {
              dataInfo.data.map((it, index) => {
                return <UserInfoCard userInfo={it} key={index} dropUser={dropUser} editUser={editUser}/>
              })
            }*/}
          </div>
          {/*分页*/}
          <DataTablePagination table={table}/>
        </div>

      </div>
    </div>
  </>
}

export default Page;